<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Administrator extends AdminBase {
	public function __construct()
    {
        parent::__construct();
    }

	public function index($p=1)
	{
		$container = 15;
		$search = $this->input->get('search');
		$this->db->from('admin_users');
		if(!empty($search)){
			$this->db->like('name',$search);
			$this->db->or_like('username',$search);
		}
		$count = $this->db->count_all_results();
		$ps = ceil($count/$container);
		if($p<1||$p>$ps){
			$admin_users = [];
		}else{
			if(!empty($search)){
				$this->db->like('name',$search);
				$this->db->or_like('username',$search);
			}
			$this->db->select('id,name,username,created_at');
			$this->db->limit($container, ($p-1)*$container);
			$admin_users = $this->db->get('admin_users')->result_array();
		}
		$pagenation = '';
		if($ps>1){
			$pagenation .='<nav aria-label="Page navigation pull-right"><ul class="pagination">';
			for ($i=1; $i<=$ps; $i++){
				if($i==1){
					$disabled = $p==1?' class="disabled"':'';
					$preUrl = $p==1?'#':site_url("admin/administrator/index/".($p-1));
					$pagenation .='<li'.$disabled.'><a href="'.$preUrl.'" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
				}
				$active = $i==$p?' class="active"':'';
				$pagenation .='<li'.$active.'><a href="'.site_url("admin/administrator/index/".$i).'">'.$i.'</a></li>';
				if($i==$ps){
					$disabled = $p==$ps?' class="disabled"':'';
					$nextUrl = $p==$ps?'#':site_url("admin/administrator/index/".($p+1));
					$pagenation .='<li'.$disabled.'><a href="'.$nextUrl.'" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>';
				}
			}
			$pagenation .='</ul></nav>';
		}
		$this->admin_view('administrator','后台用户列表',array('users'=>$admin_users,'pagenation'=>$pagenation,'search'=>empty($search)?'':$search));
	}

	public function form(){
		$data = $this->input->post();
		if($data['name']==''){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'用户名不能为空！')));
				return;
		}
		if(strlen($data['name'])<1){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'用户名过短！')));
				return;
		}
		if(strlen($data['name'])>20){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'用户名过长！')));
				return;
		}
		if($data['username']==''){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'邮箱不能为空！')));
				return;
		}
		if(!self::emailValidator($data['username'])){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'邮箱格式不正确！')));
				return;
		}

		$email_user = $this->db->get_where('admin_users',array('username'=>$data['username']))->row_array();

		if(isset($data['id'])){
			if(!empty($email_user)){
				if($email_user['id']!=$data['id']){
					$this->output->set_content_type('application/json')
					 ->set_output(json_encode(array('statu' => 'failed','message'=>'邮箱被注册！')));
					return;
				}
			}
			$this->db->where('id', $data['id']);
			$bool = $this->db->update('admin_users', $data);
			if($bool){
				$this->session->name = $data['username'];
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'修改成功！')));
				return;
			}else{
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'修改失败！')));
				return;
			}
			
		}else{
			if(!empty($email_user)){
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'邮箱被占用！')));
				return;
			}
			$data['created_at'] = date('Y-m-d H:i:s',time());
			$data['password'] = password_hash('admin123456', PASSWORD_DEFAULT);
			$bool = $this->db->insert('admin_users',$data);
			if($bool){
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'增加成功！')));
				return;
			}else{
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'增加失败！')));
				return;
			}
		}
	}

	public function delete(){
		$id = $this->input->post('id');
		if($id==1){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'不允许删除网站管理员！')));
				return;
		}
		$bool = $this->db->delete('admin_users',array('id'=>$id));
		if($bool){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'删除成功！')));
				return;
		}else{
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'删除失败！')));
				return;
		}
	}

	public function resetpassword(){
		$id = $this->input->post('id');
		if(!$id==1){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'不允许重置网站管理员的密码！网站管理员只能在个人设置中修改密码！')));
				return;
		}
		$user = $this->db->get_where('admin_users',array('id'=>$id))->row_array();
		$pass = self::getRandPassword();
		$this->db->where('id', $id);
		$bool = $this->db->update('admin_users',array('password'=>$pass['hash']));
		if($bool){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'密码重置成功！请妥善保管<br/>账户:'.$user['username'].'<br/>密码:'.$pass['password'])));
				return;
		}else{
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'密码重置失败！')));
				return;
		}
	}
	private function emailValidator($attribute, $allowName = false) {
        $pattern = "/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/";
        $fullPattern = "/^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$/";
        $valid = preg_match($pattern, $attribute) || $allowName && preg_match($fullPattern, $attribute);
        return $valid;
    }

    private function getRandPassword(){
    	$this->load->library('encryption');
    	$password = bin2hex($this->encryption->create_key(4));
    	$hash = password_hash($password, PASSWORD_DEFAULT);
    	return array('password'=>$password,'hash'=>$hash);
    }


}
